import { BrowserView, BrowserWindow } from "electron"
import { EventEmitter } from "events"
import { v1 } from 'uuid'
declare const MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY: string;

export type BrowserViewValue = {
  id: string,
  apptag: string,
  view: BrowserView
}

export class GlobalBrowsViewsMng extends EventEmitter {
  // main window
  static browserWindow: BrowserWindow = null
  private values: { [key: string]: any } = {}
  private browserViews: BrowserViewValue[] = []

  constructor() {
    super()
  }
  // 创建主进程
  createBrowserWindow(o: object = {
    show: false,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webviewTag: true,
      preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
      webSecurity: false
    }
  }): BrowserWindow {
    const win = new BrowserWindow(o)
    return GlobalBrowsViewsMng.browserWindow = win
  }

  createView(apptag: string): BrowserViewValue {
    const o = {
      view: new BrowserView({
        webPreferences: {
          nodeIntegration: true,
          contextIsolation: false,
          webviewTag: true,
          preload: MAIN_WINDOW_PRELOAD_WEBPACK_ENTRY,
          webSecurity: false
        }
      }),
      id: v1(),
      apptag: apptag
    }
    this.addBrowserView(o)
    // o.view.webContents.openDevTools();
    o.view.webContents.executeJavaScript(`window.inbroserview = true;`);
    return o
  }

  removeBrowserView(id: string) {
    let i = 0;
    for (i = 0; i < this.browserViews.length; i++) {
      if (this.browserViews[i].id === id) {
        break;
      }
    }
    GlobalBrowsViewsMng.browserWindow.removeBrowserView(this.browserViews[i].view)
    this.browserViews.splice(i, 1)
  }

  addBrowserView(view: BrowserView | BrowserViewValue, apptag: string = 'public') {
    let value: BrowserViewValue = null
    if (view instanceof BrowserView) {
      const found = this.browserViews.filter((b: BrowserViewValue) => b.view.webContents.id === view.webContents.id)
      if (!found.length) {
        value = {
          id: v1(),
          apptag: apptag,
          view: view
        }
        this.browserViews.push(value)
      }
    } else {
      let found = this.browserViews.filter((b: BrowserViewValue) => {
        let f = b.id === view.id
        f = f || (b.view.webContents.id === view.view.webContents.id)
        return f
      })
      if (!found.length) {
        this.browserViews.push(view)
      }
    }
    return this
  }

  getBrowserView(find: BrowserView | string) {
    if (find instanceof BrowserView) {
      const id = find.webContents.id
      const found = this.browserViews.filter((b: BrowserViewValue) => b.view.webContents.id === id)
      return found.length ? found[0] : null
    } else {
      const id = find
      const found = this.browserViews.filter((b: BrowserViewValue) => b.id === find)
      return found.length ? found[0] : null
    }
  }

}

export default new GlobalBrowsViewsMng()